import axios from 'axios';
import { useUserStore } from '@/stores/user';
import { ElMessage, ElLoading } from 'element-plus';
import router from '@/router';
import type { LoadingInstance } from 'element-plus/es/components/loading/src/loading.mjs';

// 创建一个加载服务实例
let loadingInstance: LoadingInstance | undefined;

const instance = axios.create({
  timeout: 10000,
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    config.headers.token = userStore.token;

    // 显示加载动画
    loadingInstance = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    });

    return config;
  },
  (err) => Promise.reject(err),
);

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    // 关闭加载动画
    closeLoading();

    if (res.data.code === 1) {
      return res;
    }
    ElMessage({
      message: res.data.msg || '服务异常',
      type: 'error',
    });
    return Promise.reject(res.data);
  },
  (err) => {
    // 关闭加载动画
    closeLoading();

    if (err.response?.status === 401) {
      router.push('/login');
    }
    ElMessage({
      message: err.response?.data?.msg || '服务异常',
      type: 'error',
    });
    return Promise.reject(err);
  },
);

function closeLoading() {
  if (loadingInstance) {
    loadingInstance.close();
  }
}

export default instance;
